package com.treasure.mall.biz.repository.product;

import com.treasure.mall.biz.base.JpaSearchableRepository;
import com.treasure.mall.biz.entity.product.ProductPO;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wm
 */
@Repository
public interface ProductRepository extends JpaSearchableRepository<ProductPO, Long> {
    /**
     * 增加锁定库存
     *
     * @param productId
     * @param store
     * @param version
     * @return
     */
    @Query("update ProductPO product set product.freeze=product.freeze+?2,product.version=product.version+1 " +
            "where product.version=?3 and product.store-?2>=0 and product.productId=?1")
    @Modifying
    @Transactional
    int addLockedStore(Long productId, int store, long version);


    /**
     * 扣减实际库存
     *
     * @param productId
     * @param store
     * @param version
     * @return
     */
    @Query("update ProductPO product set product.store=product.store-?2,product.version=product.version+1 " +
            "where product.version=?3 and product.store-?2>0 and product.productId=?1")
    @Modifying
    @Transactional
    int minusStore(Long productId, int store, long version);

    @Query("update ProductPO product set product.store=product.store+?2,product.freeze=product.freeze+?3 " +
            "where product.productId=?1 and product.store+?2>0 and product.freeze+?3>0")
    @Modifying
    @Transactional
    int updateStores(Long productId, int store, int lockedStore);

    /**
     * 查询当前类目下的商品数量
     *
     * @param categoryId
     * @return
     */
    @Query("select count(product) from ProductPO  product where product.category.catId=?1")
    long countByCategory(Long categoryId);
}